<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Common\Api\UserApi;
use Admin\Common\POMNetTools;
use Admin\Common\POMVIPClient;
class PreOrderController extends BaseController {
    private $adminUser = null;
    public function _initialize(){
    	parent::_initialize();
    	$this->adminUser = new UserApi();

    }
	
    public function index(){
      $this->display();
    }

    // 获取所有品牌
    public function PreOrderbrand(){
       $model = M('yw_brand_type','jxc_','JxcDbConfig');
       $list = $model->order('sort ASC') ->select();
       foreach ($list as $key => $value) {
         $lists = M('yw_brand','jxc_','JxcDbConfig')->field(" REPLACE(brand_name,'\'',\"‘\") AS brand_name ,brand_id")->where('typeid = '.$value['id'])->select();
         if(!empty($lists)){
           foreach ($lists as $k => $v) {
             $brand_goods = M('yw_goods','jxc_','JxcDbConfig')->where('brand_id = '.$v['brand_id'])->find();
             if($brand_goods == null ){
              unset($lists[$k]);
             }
           }
           $value['lists'] = $lists;
         }
         if(empty($value['lists'])){
           unset($list[$key]);
         }else{
          $list[$key] = $value;
         }
       }
       // print_r($list);exit;
       $this->assign('list',$list);
       $this->display('brand');
    }


   public function PreOrderList(){
          $brand_ids = I('request.brand_ids','','trim');
          if(!empty($brand_ids)){
             $where['a.brand_id'] = array('in',$brand_ids);
          }

          $title =I('request.title','','trim');
        if(!empty($title)){
           $where['a.goods_sn | a.bar_code'] =array('like',"%{$title}%");
           // print_r($_where);exit;
           // $_where['parcelname']=array('like',"%{$keywords}%");
        }

          $goods_name =I('request.goods_name','','trim');
        if(!empty($goods_name)){
           $goods_name= str_replace('‘','\'',$goods_name);
           $arr= explode('\'',$goods_name);
           if($arr[1]!= '' && strlen($arr[1]) >2){
             $where["a.goods_name"] =array('like',array("%{$arr[0]}%","%{$arr[1]}%"),'AND');
           }else{
             $where["a.goods_name"] =array('like',"%{$arr[0]}%");
           }
        }
       $tel =I('request.tel','','trim');
        if(!empty($tel)){
           $where['tel'] =array('like',"%{$tel}%");
        }
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');

        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
        if(!(empty($start_time) && empty($end_time))){ 
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }  

         $start_time = strtotime($start_time);
         $end_time = strtotime($end_time);
          $where['create_time'] = array(between,array($start_time,$end_time));
           // $str =" and create_time between '".time($start_time)."' and '".time($end_time)."'"; 
        } 


        //中文搜索商品
         $chinese_goods_name = I('request.chinese_goods_name','','trim');
         if($chinese_goods_name!=''){
              $POMVIPClient = new POMVIPClient();
              $goods =  $POMVIPClient->SearchChineseGoods($chinese_goods_name);
                $goods_arr = array();
                foreach ($goods as $key => $value) {
                   array_push($goods_arr, $value['goods_sn']);
                }
                  $goods_sn_str = implode(',',$goods_arr);
                 // print_r($goods_sn_str);exit;
                 $where['a.goods_sn'] = array('in',$goods_sn_str);
         }
         
        // $where['b.istype'] = "PUB";
        
        $_where_order_field["listrows"] =I("request._listrows");
        $_where_order_field["where"] = $where;
        $_where_order_field["field"] = 'a.*,b.quantity';
        $_where_order_field['alias']="a";
        $_where_order_field["order"] = 'a.goods_id desc';
        $_where_order_field["join"] =array('left join jxc_vip_inventory b on a.goods_sn = b.goods_sn');
        $_datalist= $this->_getListsFromModel(M('yw_goods','jxc_','JxcDbConfig'),$_where_order_field);
        // print_r($_datalist['lists']);exit;
        $POMVIPClient = new POMVIPClient();
        foreach ($_datalist['lists'] as $key => $value) {
          //获取库存
          // if($value['quantity']<=0){
          //   unset($_datalist['lists'][$key]);
          //   continue;
          // }
            $myArr = $POMVIPClient->GetStockPriQuantity($value['goods_sn']);
            $priceArr=json_decode( $POMVIPClient->GetPriceForGoodsSnOrBarcode($value['goods_sn']),true);
            // 获取价格
            $value['goods_price'] = $priceArr['Price'];
            $value['my_quantity'] = $myArr['Quantity'];
            $_datalist['lists'][$key] = $value;

        }
        $this->assign('array',$array);
        $this->assign('lists',$_datalist);
        $this->display();
   }




 public function confirm_pre_order(){
   $this->display();

 }
 public function sub_purchase_order(){
    $title = I('request.title','','trim');
    $GoodsJsonStr = I('request.GoodsJsonStr','','trim');

    //计算价格  该用户余额是否够该次采购
    $data = json_decode($GoodsJsonStr,true);
    $sum_price =0;
    foreach ($data as $key => $value) {
      $sum_price += $value['price']*$value['Quantity'];
    }
   $POMVIPClient = new POMVIPClient();
   if(!$POMVIPClient->checkUserMoney($sum_price)){
      $res = array('state'=>0,'msg'=>"您的余额不足，请先充值");
        $this->ajaxreturn($res);exit;
     }
    
    $UserId = $_SESSION['admin_user']['id'];
    $re = $POMVIPClient->PlaceAdvanceOrder($title,$UserId,$GoodsJsonStr);
     if($re == ""){

       $this->ajaxreturn(array('state'=>1,'msg'=>'采购单添加成功','money'=> $this->balance_list() ));
     }
      $this->ajaxreturn(array('state'=>0,'msg'=>$re));
 }
}
